//
//  Progress.m
//  MY QQapp
//
//  Created by liuchengming on 16/11/17.
//  Copyright © 2016年 liuchengming. All rights reserved.
//

#import "Progress.h"

@interface Progress () <NSURLSessionDataDelegate>
@property (weak, nonatomic) IBOutlet UIButton *start;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIProgressView *progress;
@property (strong,nonatomic) NSMutableData * mudata;
@property (weak, nonatomic) IBOutlet UILabel *loging;

@end

@implementation Progress

- (void)viewDidLoad {
    [super viewDidLoad];
    //self.progress = [UIProgressView new];
    self.progress.progress = 0;
    self.imageView.image = [UIImage imageNamed:@"tongyong"];
    self.loging.text = @"";
}


- (IBAction)onStart:(id)sender
{
    if(!_mudata)
    {
        //http://img1.imgtn.bdimg.com/it/u=2691548748,3110139275&fm=21&gp=0.jpg
        NSURL * url = [NSURL URLWithString:@"http://image.baidu.com/search/down?tn=download&word=download&ie=utf8&fr=detail&url=http%3A%2F%2Fwww.bz55.com%2Fuploads%2Fallimg%2F150612%2F139-150612164602-50.jpg&thumburl=http%3A%2F%2Fimg1.imgtn.bdimg.com%2Fit%2Fu%3D1973941799%2C1503249452%26fm%3D21%26gp%3D0.jpg"];
        NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
        NSURLSessionDataTask * task = [session dataTaskWithURL:url]     ;
        [task resume];
    }
}

- (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    float i = (float)dataTask.countOfBytesReceived / (float)dataTask.countOfBytesExpectedToReceive ;
    self.progress.progress = i;
    
    if(!self.mudata)
    {
        self.mudata = [NSMutableData new];
    }
    [_mudata appendData:data];
    NSLog(@"%@",self.mudata);
    
    NSString * str = [NSString stringWithFormat:@"正在加载%f",i*100];
    self.loging.text = str;
    
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    self.imageView.image = [UIImage imageWithData:self.mudata];
    self.loging.text = @"OK";
    self.progress.progress = 1;  	
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
